import type { HttpContext } from '@adonisjs/core/http'

import Member from '#models/member'
import { createMemberValidator, updateMemberValidator } from '#validators/member'
import app from '@adonisjs/core/services/app'

export default class MemberController {
  list() {
    const result: any = []

    return result
  }

  async create(ctx: HttpContext) {
    const data = await ctx.request.validateUsing(createMemberValidator)
    return await Member.create(data)
  }

  async detail({ request }: HttpContext) {
    return await Member.findOrFail(request.param('id'))
  }

  async update(ctx: HttpContext) {
    const data = await ctx.request.validateUsing(updateMemberValidator)
    const user = await Member.findOrFail(ctx.request.param('id'))
    return await user.merge(data).save()
  }

  async delete({ request }: HttpContext) {
    const user = await Member.findOrFail(request.param('id'))
    return await user.delete()
  }

  async uploadAvatar(ctx: HttpContext) {
    const avatarImage = ctx.request.file('file', {
      size: '3mb',
      extnames: ['jpg', 'png', 'gif'],
    })

    if (avatarImage) {
      await avatarImage.move(app.makePath('uploads'), {
        name: `${globalThis.wxPayload!.id}.${avatarImage.extname}`,
      })
    }

    return 'ok'
  }
}
